﻿using Microsoft.Extensions.Configuration;
using MongoDB.Bson;
using MongoDB.Driver;
using Newtonsoft.Json.Linq;
using Pangeo.Admin.Models;

namespace Pangeo.Admin.Services.HrmDb
{
    public class _ServerBase
    {
        public IMongoDatabase db;

        public _ServerBase(IConfiguration config)
        {
            var url = config.GetConnectionString("HrmDb");
            db = new MongoClient(url).GetDatabase("gisiclouds");
        }

        /// <summary>
        /// 查询方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tableName">查询的集合</param>
        /// <param name="scriptName">脚本文件名</param>
        /// <param name="timeRange">起止日期</param>
        /// <returns></returns>
        public Result<List<T>> Query<T>(string tableName = null, string scriptName = null, Dictionary<string, DateTime> timeRange = null)
        {
            var res = new Result<List<T>>();

            try
            {
                if(tableName == null)
                {
                    tableName = typeof(T).Name;
                    if (string.IsNullOrEmpty(tableName))
                        return res;
                }

                var collection = db.GetCollection<BsonDocument>(tableName.ToLower());

                if (scriptName == null)
                {
                    scriptName = typeof(T).Name;
                    if (string.IsNullOrEmpty(scriptName))
                        return res;
                }

                // 获取对应脚本
                var script = File.ReadAllText($"Scripts/{scriptName}.js");

                // 处理自定义参数
                if (timeRange != null)
                {
                    foreach (var param in timeRange)
                        script = script.Replace($"@{param.Key}", param.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss"));
                }

                // 解析脚本到JSON数组
                var jsonArray = JArray.Parse(script);

                // 创建就和管道
                var pipelines = new List<BsonDocument>();

                // 遍历JSON数组中的每个对象并输出信息
                foreach (JObject obj in jsonArray)
                    pipelines.Add(BsonDocument.Parse(obj.ToString()));

                // 定义聚合管道对象
                var aggregationPipeline = PipelineDefinition<BsonDocument, T>.Create(pipelines);

                // 执行聚合查询并将结果映射到指定类
                res.Data = collection.Aggregate(aggregationPipeline).ToList();

                res.Success = true;
            }
            catch (Exception ex)
            {
                res.Message = ex.Message;
            }

            return res;
        }
    }
}
